<template>
	<view class="detail-view">
		<u-form label-width="160" :model="add_form" ref="uForm">
			<view class="form-model-view">
				<u-form-item required label="采购仓库" prop="warehouseName">
					<u-input @click="goPage('/pagesT/werahouse/selWerahouse')" class="dis-input" disabled v-model="add_form.warehouseName" placeholder="请选择" />
					<u-icon name="arrow-right" size="24" color="#6c6c6c"></u-icon>
				</u-form-item>
				<u-form-item required label="供应商" prop="supplierName">
					<u-input @click="goPage('/pagesT/supplier/selSupplier')" class="dis-input" disabled v-model="add_form.supplierName" placeholder="请选择" />
					<u-icon name="arrow-right" size="24" color="#6c6c6c"></u-icon>
				</u-form-item>
				<u-form-item required label="采购员" prop="buyerName">
					<u-input @click="goPage('/pagesT/staff/selStaff')" class="dis-input" disabled v-model="add_form.buyerName" placeholder="请选择" />
					<u-icon name="arrow-right" size="24" color="#6c6c6c"></u-icon>
				</u-form-item>
			</view>
			<view class="form-model-view">
				<u-form-item required label="商品清单">
					<view @click="selGoodsPage" class="form-value add-btn-go">
						<u-icon name="plus" size="24" color="#fb5904"></u-icon>
						<text class="form-value add-text">选择商品</text>
					</view>
				</u-form-item>
				<view class="goods-ul" v-if="goods_list.length">
					<view class="goods-title clearfix" @click="goMoreGoods">
						<view class="float_left">请核对已选商品</view>
						<view class="float_right">编辑</view>
					</view>
					<block v-for="(item, index) in goods_list" :key="index">
						<view class="goods-li clearfix" v-if="index < 6">
							<view class="goods-img float_left"><u-icon size="40" name="shangpin" custom-prefix="custom-icon" color="#cccccc"></u-icon></view>
							<view class="float_left info">
								<view class="goods-name ellipsis">{{ item.goodsName }}</view>
								<view class="goods-code clearfix">
									<view class="float_left">{{ item.goodsCode }}</view>
									<view class="float_right">x{{ $utils.formatNub(item.buyerNum) }}</view>
								</view>
								<view class="goods-num clearfix">
									<view class="float_left">{{ item.unitName }};{{ item.specGropName }}</view>
									<view @click="goMoreGoods" class="float_right" v-if="item.isEq === 5">
										其他单位：
										<text v-if="Number(item.otherNum) > 0">{{ $utils.formatNub(item.otherNum) }}</text>
										<text v-else style="color: #FB5904;">编辑</text>
									</view>
								</view>
								<view class="goods-num clearfix" v-if="item.skuValue">
									<view class="float_left">换算比例:{{ item.skuValue }}</view>
									<text class="float_right">转换数量:{{ item.skuNum }}</text>
								</view>
								<view class="goods-num clearfix">
									<view class="float_left ">
										<text class="price">{{ $utils.formattedNumber(item.buyerUnitPrice) }}</text>
									</view>
									<view class="float_right">
										小计：
										<text class="price">{{ $utils.formattedNumber(item.subtotalPrice) }}</text>
									</view>
								</view>
							</view>
						</view>
					</block>
					<view @click="goMoreGoods" class="more-goods" v-if="goods_list.length >= 6">
						查看更多商品
						<u-icon name="arrow-right" size="24" color="#6c6c6c"></u-icon>
					</view>
				</view>
			</view>
			<view class="form-model-view">
				<u-form-item label="其他金额">
					<input type="digit" v-model="add_form.otherAmount" class="dis-input" placeholder="请输入" />
					<text class="rem-unit">元</text>
				</u-form-item>
				<u-form-item label="优惠金额">
					<input type="digit" v-model="add_form.couponAmount" class="dis-input" placeholder="请输入" />
					<text class="rem-unit">元</text>
				</u-form-item>
				<u-form-item label="合计">
					<input type="digit" v-model="purchaseAmount" class="dis-input" placeholder="请输入" />
					<text class="rem-unit">元</text>
				</u-form-item>
			</view>
		</u-form>
		<view class="detail-bottom"><view class="handel-btn" @click="submit">提交订单</view></view>
	</view>
</template>

<script>
const goods = {
	basicGoodsId: '',
	goodsCode: '',
	goodsName: '',
	skuId: '',
	unitName: '',
	categoryId: '',
	categoryName: '',
	buyerNum: 0, 
	buyerUnitPrice: 0,
	subtotalPrice: 0,
	couponAmount: 0,
	otherAmount: 0
};
export default {
	data() {
		return {
			err_tip_list: [], // 错误提示
			rules: {
				warehouseName: [
					{
						required: true,
						message: '请选择采购仓库',
						trigger: ['change', 'blur']
					}
				],
				supplierName: [
					{
						required: true,
						message: '请选择供应商',
						trigger: ['change', 'blur']
					}
				],
				buyerName: [
					{
						required: true,
						message: '请选择采购员',
						trigger: ['change', 'blur']
					}
				]
			},
			goods_id: [],
			werahouseData: '',
			supplierData: '',
			staffData: '',
			goodsData: '',
			purchaseGoods: '',
			goods_num: '',
			add_form: {
				code: '',
				shopId: '',
				shopName: '',
				supplierId: '',
				supplierName: '',
				buyerId: '',
				buyerName: '',
				operatorName: '',
				couponAmount: 0,
				otherAmount: 0,
				remark: '',
				goodsData: [],
				warehouseName: '',
				warehouseId: '',
				purchaseType: 4
			},
			goods_list: []
		};
	},
	computed: {
		userName() {
			return this.$store.state.userInfo.name;
		},
		purchaseAmount() {
			let sum = 0;
			if (this.goods_list.length > 1) {
				this.goods_list.forEach(item => {
					sum = this.$NP.plus(sum, Number(item.subtotalPrice));
				});
			} else if (this.goods_list.length === 1) {
				sum = Number(this.goods_list[0].subtotalPrice);
			} else {
				sum = 0;
			}
			return this.$NP.plus(sum, this.$NP.minus(this.add_form.otherAmount, this.add_form.couponAmount)) || 0;
		}
	},
	watch: {
		werahouseData(val) {
			if (val) {
				this.add_form.warehouseId = val.id;
				this.add_form.warehouseName = val.warehouseName;
			}
		},
		supplierData(val) {
			if (val) {
				this.add_form.supplierId = val.id;
				this.add_form.supplierName = val.title;
			}
		},
		staffData(val) {
			if (val) {
				this.add_form.buyerId = val.id;
				this.add_form.buyerName = val.staffName;
			}
		},
		// 选择商品资料页面返回
		goodsData(list) {
			if (list) {
				this.selGoods(list);
			}
		},
		// 已选择采购商品页面返回
		purchaseGoods(list) {
			if (list) {
				this.goods_list = list;
			}
		}
	},
	// 必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
	onReady() {
		this.$refs.uForm.setRules(this.rules);
	},
	onLoad(options) {
		if (options.id) {
			this.purchase_id = options.id;
			uni.setNavigationBarTitle({
				title: '编辑采购单'
			});
			this.getPurchaseInfoById();
		}
		// 	// 获取sku换算关系
		// 	this.getSkuNum();
		// });
	},
	methods: {
		selGoodsPage() {
			uni.setStorageSync('purGoods', this.goods_list);
			this.goPage('/pagesT/goods/selGoodsBasicBySku?pageName=purchase');
		},
		goMoreGoods() {
			uni.setStorageSync('PurchaseGoods', this.goods_list);
			this.goPage(`/pagesT/Purchase/PurchaseGoods`);
		},
		// 详情
		getPurchaseInfoById() {
			this.$u.api.getPurchaseInfoById(this.purchase_id).then(({ data }) => {
				this.add_form = {
					code: data.code,
					shopId: data.shopId,
					shopName: data.shopName,
					supplierId: data.supplierId,
					supplierName: data.supplierName,
					buyerId: data.buyerId,
					buyerName: data.buyerName,
					operatorName: data.operatorName,
					couponAmount: data.couponAmount,
					otherAmount: data.otherAmount,
					remark: data.remark,
					goodsData: data.details,
					warehouseName: data.warehouseName,
					warehouseId: data.warehouseId,
					purchaseType: 4
				};
				// 商品
				this.goods_list = data.details.map(item => {
					return {
						...item,
						skuId: item.skuId,
						specGropName: item.skuName
					};
				});
				// 获取sku换算关系
				this.getSkuNum();
			});
		},
		// 多选商品确定
		selGoods(list) {
			uni.showLoading()
			const goodsD = list.map(item => {
				let specGropName = '';
				if (item.specGroup) {
					specGropName = item.specGroup
						.map(itemS => {
							return itemS.specValueName;
						})
						.join('_');
				} else {
					specGropName = item.specGropName;
				}
				const buyerNum = item.buyNum || item.buyerNum || 1;
				return {
					isEq: item.isEq,
					basicGoodsId: item.id || item.basicGoodsId,
					goodsCode: item.code,
					goodsName: item.title,
					skuId: item.skuId,
					specGropName: specGropName,
					unitName: item.unitName,
					categoryId: item.categoryId,
					categoryName: item.categoryName,
					buyerNum: buyerNum,
					buyerUnitPrice: item.buyerUnitPrice || '',
					subtotalPrice: this.$NP.times(buyerNum, item.buyerUnitPrice || 0),
					couponAmount: item.couponAmount || '',
					otherAmount: item.otherAmount || ''
				};
			});
			const skuIdArr = goodsD.map(item => {
				return item.skuId;
			});
			this.pricePauseSave(skuIdArr, goodsD);
		},
		// 价格暂存查询
		async pricePauseSave(skuId, goodsData) {
			uni.showLoading()
			await this.$u.api
				.getMoneyPauseSave({
					skuIds: skuId
				})
				.then(({ data }) => {
					this.goods_list = goodsData.map(item => {
						return {
							...item,
							buyerUnitPrice: item.buyerUnitPrice > 0.1 ? item.buyerUnitPrice : data[item.skuId] || 0.1,
							subtotalPrice: item.subtotalPrice > 0.1 ? item.subtotalPrice : data[item.skuId] || 0.1
						};
					});
					// 获取sku换算关系
					this.getSkuNum();
				});
		},
		//换算sku数量
		getSkuNum() {
			uni.showLoading()
			const skuNum = this.goods_list
				.map(item => {
					return {
						skuId: item.skuId,
						goodsBasicId: item.basicGoodsId,
						num: Number(item.buyerNum) || 1
					};
				})
				.filter(item => item.skuId);
			if (!skuNum.length) {
				return;
			}
			this.$u.api.getMasterSkuNum(skuNum).then(({ data }) => {
				this.goods_list = this.goods_list.map(item => {
					let obj = {};
					if (data[item.skuId]) {
						obj = {
							title: data[item.skuId].title || '',
							buyerNum: data[item.skuId].num,
							skuValue: data[item.skuId].skuValue,
							skuNum: data[item.skuId].masterNum + data[item.skuId].masterName
						};
					}
					return {
						...item,
						...obj
					};
				});
				this.goMoreGoods()
			});
		},
		// 改变数量
		editNumChange(index, tag) {
			const target = this.$u.deepClone(this.goods_list);
			target[index].subtotalPrice = (target[index].buyerNum || 1) * target[index].buyerUnitPrice;
			this.goods_list = target;
			if (!target[index].skuId) return;
			if (tag === 'buyerNum') {
				// 获取sku换算关系
				this.getSkuNum();
			}
		},
		// 价格暂存提交
		async addMoneyPauseSave() {
			const priceData = this.goods_list.map(item => {
				return {
					skuId: item.skuId,
					money: item.buyerUnitPrice
				};
			});
			await this.$u.api
				.addMoneyPauseSave({
					data: priceData
				})
				.then(res => {});
		},
		submit() {
			this.$refs.uForm.validate(valid => {
				if (valid) {
					if (!this.goods_list.length) {
						this.$u.toast('请选择商品');
						return;
					}
					const isbuyerNum = this.goods_list.every(item => item.buyerNum > 0);
					if (!isbuyerNum) {
						this.$u.toast('采购数量必须大于0');
						return;
					}
					const isbuyerUnitPrice = this.goods_list.every(item => item.buyerUnitPrice > 0);
					if (!isbuyerUnitPrice) {
						this.$u.toast('采购单价必须大于0');
						return;
					}
					let goodsData = this.goods_list.map(item => {
						let goods = {
							basicGoodsId: item.basicGoodsId,
							goodsCode: item.goodsCode,
							goodsName: item.goodsName,
							skuId: item.skuId,
							unitName: item.unitName,
							skuName: item.specGropName,
							buyerNum: item.buyerNum,
							buyerUnitPrice: item.buyerUnitPrice,
							subtotalPrice: item.subtotalPrice,
							couponAmount: Number(item.couponAmount),
							otherAmount: Number(item.otherAmount),
							categoryId: item.categoryId,
							categoryName: item.categoryName,
							otherNum: item.otherNum
						};
						if (item.id) {
							goods.id = item.id;
						}
						return goods;
					});
					const params = {
						...this.add_form,
						operatorName: this.userName,
						goodsData: goodsData
					};
					if (this.purchase_id) {
						this.$u.api.editPurchase(this.purchase_id, params).then(res => {
							this.$u.toast('修改成功');
							// 价格暂存添加
							this.addMoneyPauseSave();
							setTimeout(() => {
								uni.navigateBack();
							}, 2000);
						});
					} else {
						this.$u.api.addPurchase(params).then(res => {
							this.$u.toast('新建成功');
							// 价格暂存添加
							this.addMoneyPauseSave();
							setTimeout(() => {
								uni.navigateBack();
							}, 2000);
						});
					}
				}
			});
		}
	}
};
</script>

<style lang="scss" scoped>
	.form-value{
		.add-text{
			color: #fb5904;
		}
	}
.goods-ul {
	.more-goods {
		line-height: 80rpx;
		border-top: 1px solid #eeeeee;
		text-align: center;
		font-size: 24rpx;
	}

	.goods-title {
		margin-bottom: 20rpx;
		line-height: 80rpx;
		font-size: 24rpx;
		border-bottom: 1px solid #eeeeee;

		.float_right {
			color: $uni-color-primary;
		}
	}

	.goods-li {
		line-height: 32rpx;
		padding-bottom: 24rpx;

		.goods-img {
			margin-right: 20rpx;

			image {
				width: 150rpx;
				height: 150rpx;
				border-radius: 8rpx;
				display: block;
			}
		}

		.info {
			.goods-name {
				width: 640rpx;
				height: 34rpx;
				line-height: 34rpx;
			}

			.goods-code {
				font-size: 24rpx;
				padding-top: 10rpx;
			}

			.goods-num {
				padding-top: 10rpx;
				font-size: 24rpx;

				.price {
					font-size: 28rpx;
					font-weight: bold;
					color: $uni-color-error;
				}
			}
		}
	}
}
.detail-bottom {
  .handel-btn {
    background: #fb5904; 
	border-color: #fb5904;
  }
}
</style>
